/**
 * 自定义选择框
 * */
;!function (window) {
    "use strict";

    var isLucky = window.lucky && lucky.define, $, win, ready = {
        getPath: function(){
            var jsPath = document.currentScript ? document.currentScript.src : function(){
                var js = document.scripts
                    ,last = js.length - 1
                    ,src;
                for(var i = last; i > 0; i--){
                    if(js[i].readyState === 'interactive'){
                        src = js[i].src;
                        break;
                    }
                }
                return src || js[last].src;
            }();
            return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
        }(),

        //获取节点的style属性值
        getStyle: function(node, name){
            var style = node.currentStyle ? node.currentStyle : window.getComputedStyle(node, null);
            return style[style.getPropertyValue ? 'getPropertyValue' : 'getAttribute'](name);
        },

        //载入CSS配件
        link: function(href, fn, cssname){
            //未设置路径，则不主动加载css
            if(!select.path) return;

            var head = document.getElementsByTagName("head")[0], link = document.createElement('link');
            if(typeof fn === 'string') cssname = fn;
            var app = (cssname || href).replace(/\.|\//g, '');
            var id = 'selectcss-'+ app, timeout = 0;

            link.rel = 'stylesheet';
            link.href = select.path + href;
            link.id = id;

            if(!document.getElementById(id)){
                head.appendChild(link);
            }

            if(typeof fn !== 'function') return;

            //轮询css是否加载完毕
            (function poll() {
                if(++timeout > 8 * 1000 / 100){
                    return window.console && console.error('select.css: Invalid');
                };
                parseInt(ready.getStyle(document.getElementById(id), 'width')) === 1989 ? fn() : setTimeout(poll, 100);
            }());
        }
    };

    var doms = ["lucky-select", "lucky-select-hidden", "lucky-select-container--open", "lucky-select-container--disabled", "lucky-select-selection",
        "lucky-select-dropdown", "lucky-select-dropdown--below", "lucky-select-dropdown--above", "lucky-select-container--below", "lucky-select-container--above",
        "lucky-select-search", "lucky-select-results__option", "lucky-select-results__option--highlighted", "lucky-select-selection__rendered"];

    var select = {
        path: ready.getPath,
        ready: function (callback) {
            var cssname = 'select' ,path = (isLucky ? 'forms/select/' : 'theme/') + 'select.css?v='+ new Date().getTime();
            isLucky ? lucky.addcss(path, callback, cssname) : ready.link(path, callback, cssname);
            return this;
        },
        destroy: function(element){

        }
    };

    var SelectClass = function (element, options) {
        var that = this;
        that.element = $(element);
        that.config = $.extend({}, that.config, options);
        console.log("开始渲染Select");
        that.init();
    };

    SelectClass.prototype.config = {
        placeholder: "请选择",
        search: false,
        multiple: false,
        disabled: false,
        /**
         * [{
         *      icon: "",
         *      text: "",
         *      value: "",
         *      selected: boolean,
         *      disabled: boolean,
         *      children:[{
         *
         *      }]
         * }]
         * */
        dataItems:[]
    };

    SelectClass.prototype.init = function () {
        var that = this,
            hasRender = that.element.next("." + doms[0]), selectWidth = that.element.outerWidth();
        //读取select属性初始化
        that.readAttributeInitConfig();

        //隐藏原始select
        if(!that.element.hasClass("." + doms[1])){
            that.element.addClass(doms[1]);
        }

        //如果已经渲染，则删除
        hasRender[0] && hasRender.remove();

        //创建
        that.create(function(htmlDom){
            that.element.after(htmlDom);
            that.select = htmlDom;
            //更新select尺寸
            that.select.width(selectWidth);
            //这里需要开始初始化相关事件了。。。
            that.events();
        });
    };

    SelectClass.prototype.readAttributeInitConfig = function () {
        var that = this;
        //读取 select placeholder
        that.config.placeholder = that.element.attr("placeholder") ? that.element.attr("placeholder") : that.config.placeholder;
        that.config.disabled = that.element.attr("disabled") ? true : that.config.disabled;
        that.config.multiple = that.element.attr("multiple") ? true : that.config.multiple;

        that.config.search = that.element.attr("lucky-search") !== undefined ? true : that.config.search;
    };

    SelectClass.prototype.create = function (callback) {
        var that = this, config = that.config, select = that.element, selectedValue = select.val();
        var selectElem = $([
            '<div class="lucky-select lucky-select-container lucky-select-container--default lucky-select-container--below ' + (config.disabled ? doms[3]:'') + '">'
                ,'<div class="selection">'
                    ,'<div class="lucky-select-selection lucky-select-selection--single">'
                        ,'<span class="lucky-select-selection__rendered">' + config.placeholder + '</span>'
                        ,'<span class="lucky-select-selection__arrow" role="presentation"><b role="presentation"></b></span>'
                    ,'</div>'
                ,'</div>'
                ,'<div class="lucky-select-dropdown lucky-select-dropdown--below">'
                    , config.search ? (function(){
                            return "<div class=\"lucky-select-search lucky-select-search--dropdown\"><input class=\"lucky-select-search__field\" type=\"search\" /></div>";
                        }()) : ''
                    , '<div class="lucky-select-results">'
                        ,'<ul class="lucky-select-results__options">'
                            , (function(options){
                                var arr = [], recordValue = [];
                                options.each(function (index, item) {
                                    var $option = $(this);
                                    if (!$option.is('option') && !$option.is('optgroup')) {
                                        return;
                                    }
                                    if($option.is('option') && $.inArray($option.val(), recordValue) == -1){
                                        arr.push('<li class="lucky-select-results__option" role="item" value="' + $option.val() + '"  '+ (item.disabled ? (' '+"aria-disabled=\"true\"") : '') +' aria-selected="' + (selectedValue === $option.val() ? "true":"false" ) + '">' + $option.text() + '</li>');
                                        recordValue.push($option.val());
                                    }else if($option.is('optgroup')){
                                        arr.push('<li class="lucky-select-results__option" role="group">');
                                        arr.push('<strong class="lucky-select-results__group">' + item.label + '</strong>');
                                        arr.push('<ul class="lucky-select-results__options lucky-select-results__options--nested">');
                                        $option.find("*").each(function(index, child){
                                            var $child = $(this);
                                            if($child.is('option')){
                                                arr.push('<li class="lucky-select-results__option" role="item" value="' + $child.val() + '" '+ (child.disabled ? (' '+"aria-disabled=\"true\"") : '') +' aria-selected="' + (selectedValue === $child.val() ? "true":"false" ) + '">' + $child.text() + '</li>');
                                                recordValue.push($child.val());
                                            }
                                        });
                                        arr.push('</ul>');
                                        arr.push('</li>');
                                    }
                                });
                                arr.length === 0 && arr.push('<li class="lucky-select-results__option lucky-select-results__message">没有选项</li>');
                                return arr.join('');
                            }(select.find("*")))
                        ,'</ul>'
                    ,'</div>'
                ,'</div>'
            ,'</div>'
        ].join(''));

        callback(selectElem);
    };

    SelectClass.prototype.selectLocation = function () {
        var that = this;
        //上下定位识别
        var top = that.select.offset().top + that.select.outerHeight() + 5 - win.scrollTop(),
            selectDropdown = that.select.find("." + doms[5]),
            selectDropdownHeight = selectDropdown.outerHeight();

        that.select.removeClass(doms[8] + " " + doms[9]);
        selectDropdown.removeClass(doms[6] + " " + doms[7]);

        if(top + selectDropdownHeight > win.height() && top >= selectDropdownHeight){
            selectDropdown.addClass(doms[7]).css("top",(selectDropdownHeight) * -1);
            that.select.addClass(doms[9]);
        }else{
            selectDropdown.addClass(doms[6]).css("top",that.select.outerHeight());
            that.select.addClass(doms[8]);
        }
    };

    SelectClass.prototype.events = function () {
        var that = this;

        if(that.config.disabled){
            return;
        }

        function hideDropdown(){
            that.select.removeClass(doms[2] + " " + doms[8] + " " + doms[9]);
            that.select.find("." + doms[5]).removeClass(doms[6] + " " + doms[7]);
        }

        function closeDropdown(e, clear){
            if(!$(e.target).parents().hasClass(doms[5]) || clear){
                hideDropdown();
                //thatInput && initValue && thatInput.val(initValue);
            }
            //thatInput = null;
        }

        that.select.find("." + doms[4]).on("click",function(event){
            event.stopPropagation();
            that.selectLocation();
            that.toggleDropdown();
        });
        
        that.select.find("." + doms[11]).hover(
            function () {
                $(this).addClass(doms[12]);
            },
            function () {
                $(this).removeClass(doms[12]);
            }
        );
        that.select.find("." + doms[11] + "[role='item']").on("click", function(){
            var othis = $(this),
                value = othis.attr("value"),
                disabled = othis.attr("aria-disabled");

            if(disabled) return false;

            //默认是单个文本选框
            that.select.find("." + doms[13]).text(othis.text());
            that.element.val(value);

            that.select.find("." + doms[11] + "[role='item']").attr("aria-selected",false);
            othis.attr("aria-selected",true);

            hideDropdown();
        });

        //关闭下拉
        $(document).off('click', closeDropdown).on('click', closeDropdown);

        win.resize(function () {
            that.selectLocation();
        });
    };

    //显示隐藏
    SelectClass.prototype.toggleDropdown = function () {
        var that = this;
        if(that.config.disabled){
            return;
        }
        if(!that.isOpen()){
            that.select.addClass(doms[2]);
        }else{
            that.select.removeClass(doms[2]);
        }
    };

    SelectClass.prototype.isOpen = function () {
        return this.select.hasClass(doms[2]);
    };

    SelectClass.prototype.destroy = function () {

    };

    ready.run = function ($$) {
        $ = $$;
        win = $(window);
        doms.html = $('html');
        doms.body = $('body');
        select.render = function(element, options){
            var inst = new SelectClass(element, options);
            return inst;
        };
    };

    window.lucky && lucky.define ? (
        select.ready()
        , lucky.define(['jquery'], function(exports){
            select.path = lucky.cache.dir;
            ready.run(window.jQuery);

            window.select = select;
            exports('select', select);
        })
    ) : (
        (typeof define === 'function' && define.amd) ? define(['jquery'], function(){
            //requirejs加载
            ready.run(window.jQuery);
            return select;
        }) : function(){
            //普通script标签加载
            ready.run(window.jQuery);
            select.ready();
        }()
    );
}(window);